<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="留样记录">
        <template slot="btn">

        </template>
      </modules-title>
    </div>
    <div style="padding:20px">
      <el-form :inline="true">
        <el-form-item label="状态" style="margin-right:40px">
          <el-select v-model="queryParams.search_type" @change="handlSearch" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="留样有效期至">
          <el-date-picker
            style="width: 270px"
            @input="handlDate"
            v-model="value"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属项目">
          <el-select v-model="queryParams.project_id" @change="handlProject" placeholder="请选择">
            <el-option v-for="item in projectList" :key="item.value" :label="item.project_name"
                       :value="item.project_id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="样品关键字" style="margin-right:40px">
          <el-input v-model="queryParams.select_str" placeholder="请输入留样编号或样品名称"/>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" size="small"
                     @click="handleQuery">查询
          </el-button>
          <el-button plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="tableData" tooltip-effect="dark" border size="medium" @row-click="aloneClick"
                :cell-style="cellStyle" :show-overflow-tooltip="true">
        <el-table-column prop="reserve_sample_no" label="留样编号" align="center" :show-overflow-tooltip="true"/>
        <el-table-column prop="sample_info.name" label="样品名称" header-align="center" :show-overflow-tooltip="true"/>
        <el-table-column  label="样品类别" align="center"
                         :show-overflow-tooltip="true">
          <template #default="{row}">
            <span v-if="row.sample_info.sample_type_info">{{row.sample_info.sample_type_info.same_type_name	}}</span>
          </template>
        </el-table-column>
        <el-table-column  label="批号" align="center" :show-overflow-tooltip="true">
          <template #default="{row}">
            <span v-if="row.sample_info"> {{handlBatch(row.sample_info.batch_info)}}</span>
          </template>
        </el-table-column>

        <!--        <el-table-column prop="sample_info.attr" label="规格" align="center" :show-overflow-tooltip="true"/>-->
        <el-table-column label="生产日期" align="center">
          <template #default="{row}">
              <span v-if="row.sample_info !== null && row.sample_info.production_date">
                {{dateFormat1('yyyy-mm-dd',row.sample_info.production_date)}}
              </span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="留样数量" align="center">
          <template #default="{row}">
            <span>{{row.num}}</span>
            <span v-if="row.sample_info && row.sample_info.unit ">{{row.sample_info.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="project_name" label="所属项目" header-align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="留样有效期至" align="center" :show-overflow-tooltip="true" width="180">
          <template #default="{row}">
            <div>{{dateFormat1('yyyy-mm-dd ',row.expiry_date)}}</div>
            <div>{{calculate(dateFormat1('yyyy-mm-dd ',row.expiry_date))}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="留样时间" align="center" :show-overflow-tooltip="true">
          <template #default="{row}">
            {{dateFormat1('yyyy-mm-dd ',row.created_at)}}
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="留样人" align="center"/>
        <el-table-column label="状态" align="center">
          <template #default="{row}">
            <span v-if="row.status === 0">正常</span>
            <span v-else-if="row.status === 1">已销毁</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center">
          <template #default="{row}">
            <el-button type="text" v-if="row.if_commit_report === 1 && ((row.inspection_header && row.inspection_header.id === userInfo) ||
                (row.inspection_joiner && handlAbc(row.inspection_joiner)))"
                       size="medium" @click.native.stop="hanldReport(row.inspection_id)">
              查看报告
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--页码-->
      <pagination style="display:flex;justify-content:flex-end;" :total="total"
                  :page.sync="queryParams.pager.skip" :limit.sync="queryParams.pager.limit"
                  @pagination="pagination"/>
    </div>
    <!--查看报告 -->
    <reportdialog ref="reportdialog" :formOpen="formOpen" :rowList="rowList"/>

  </div>
</template>

<script>
  import { sampleList, sampleAllProject } from '@/api/samples'
  import { sampleListTable, viewReport } from '@/api/sampleInspection'

  export default {
    name: 'index',
    components: {
      reportdialog: () => import('../../../sampleInspection/modules/reportList.vue')
    },
    data() {
      return {
        value: [],
        queryParams: {
          search_type: -1,
          select_str: '',
          start_time: '',
          end_time: '',
          project_id: '',
          pager: {
            limit: 10,
            skip: 1
          }
        },
        options: [
          { value: -1, label: '全部' },
          { value: 0, label: '正常' },
          { value: 1, label: '已销毁' }
        ],
        tableData: [],
        total: 0,
        openReport: false,
        preview: ['preview'],
        fileList: [],
        fileType: undefined,
        projectList: [],
        userInfo: '',
        rowList: {},
        formOpen: {
          tableResults: {
            id: '',
            report: [],//
            computation_sheet: [], //计算表格
            inspection_map: []//  检验图谱
          },
          relation_plan_id: ''
        }
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {
      calculate() {
        return function(val) {
          let a = ''
          let date = new Date()
          let year = date.getFullYear()
          let month = date.getMonth() + 1
          month > 10 ? month : `0${month}`
          let day = date.getDate()
          day > 10 ? day : `0${day}`
          let expiry_date = `${year}-${month}-${day}`
          if (new Date(val) < new Date(expiry_date)) {
            a = '已过期'
          }
          return a
        }
      },
      handlAbc() {
        return function(val) {
          let index = val.findIndex(a => a.id === this.userInfo)
          if (index !== -1) {
            return true
          } else {
            return false
          }
        }
      },
      handlBatch() {
        return function(val) {
          let str = ''
          if (val) {
            for (let i = 0; i < val.length; i++) {
              str += val[i].sample_batch
              if (i !== val.length - 1) {
                str = str + '、'
              }
            }
          }
          return str
        }
      }
    },

    //属性是手动定义的所需监听的值
    watch: {},

    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.userInfo = this.$store.getters.userInfo.user.id
      this.hanldsampleList()
      this.handlSampleAllProject()
    },

    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {

    },

    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //时间事件
      handlDate(val) {
        if (val === null) {
          this.queryParams.start_time = ''
          this.queryParams.end_time = ''
        } else {
          this.queryParams.start_time = this.dateFormat1('yyyy-mm-dd 00:00:00', val[0])
          this.queryParams.end_time = this.dateFormat1('yyyy-mm-dd 23:59:59', val[1])
        }
        this.queryParams.pager.skip = 1
        this.hanldsampleList()

      },

      handlSampleAllProject() {
        sampleAllProject().then(res => {
          if (res.code === 200) {
            this.projectList = res.data
          }
        })
      },

      //获取留样列表数据
      hanldsampleList() {
        sampleList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.tableData = res.data.data || []
            this.total = res.data.total
          }
        })
      },

      //页码
      pagination(val) {
        this.queryParams.pager.skip = val.page
        this.queryParams.pager.limit = val.limit
        this.hanldsampleList()
      },

      handlSearch(val) {
        this.queryParams.search_type = val
        this.queryParams.pager.skip = 1
        this.hanldsampleList()
      },

      handlProject(val) {
        this.queryParams.project_id = val
        this.queryParams.pager.skip = 1
        this.hanldsampleList()
      },

      //查询
      handleQuery() {
        this.queryParams.pager.skip = 1
        this.hanldsampleList()
      },

      //重置
      resetQuery() {
        this.queryParams = {
          search_type: -1,
          select_str: '',
          start_time: '',
          end_time: '',
          project_id: '',
          pager: {
            limit: 10,
            skip: 1
          }
        }
        this.value = []
        this.hanldsampleList()
      },

      //查看详情
      aloneClick(row, column, event) {
        this.$router.push({
          path: '/sampleManagement/retention/details',
          query: { id: row.id }
        })
      },

      //鼠标huover
      cellStyle(data) {
        return 'cursor:pointer;'
      },

      //查看报告
      hanldReport(id) {

        let row = {}
        viewReport(id).then(res => {
          if (res.code === 200) {
            row = res.data
            this.rowList = row
            this.formOpen.tableResults = {
              computation_sheet: [],
              report: [],
              inspection_map: []
            }
            if (row.computation_sheet && row.inspection_result && row.inspection_map) {
              this.formOpen.tableResults.computation_sheet = JSON.parse(JSON.stringify(row.computation_sheet)) || []
              this.formOpen.tableResults.report = JSON.parse(JSON.stringify(row.inspection_result)) || []
              this.formOpen.tableResults.inspection_map = row.inspection_map || []
              for (let i = 0; i < this.formOpen.tableResults.report.length; i++) {
                this.formOpen.tableResults.report[i].boole = true
                if (row.experiment_table_info_map) {
                  this.formOpen.tableResults.report[i].ruleForm = row.experiment_table_info_map[this.formOpen.tableResults.report[i].batch_no]
                } else {
                  if (row.inspection_type === 'inspection_type_wd') {
                    sampleListTable({ id: row.relation_plan_id }).then(res => {
                      if (res.code === 200) {
                        this.formOpen.tableResults.report.forEach(item => {
                          if (res.data[item.batch_no]) {
                            item.ruleForm = res.data[item.batch_no]
                          }
                        })
                      }
                    })
                  }
                }
              }
            }
            this.$refs.reportdialog.openport()
            // this.activeNames = this.formOpen.tableResults.report[0].batch_no
          }
        })
      }
    }

  }

</script>

<style scoped>
  /* @import url(); 引入css类 */
  .el-button--text {
    padding: 0;
  }
</style>
